<template>
  <div class="base-info-page">
    <NavHeader :title="t('review.title')" :showStepProgress="false" />
    <div class="info-card-group">
      <!-- 师傅信息卡 -->
      <div class="info-card review-master-card">
        <div class="review-master-vertical">
          <div class="review-question-left">
            {{ t('review.areYouSatisfied') }}
          </div>
          <div class="review-master-row">
            <div class="master-avatar">
              <van-icon name="contact" class="vant-avatar-icon" />
            </div>
            <div class="master-info">
              <div class="master-name">
                {{ userName }}
              </div>
              <div class="master-date">{{ time }}</div>
            </div>
          </div>
        </div>
        <div class="review-satisfaction-row">
          <div :class="[
            'satisfaction-btn',
            !satisfied ? 'active' : '',
          ]" @click="satisfied = false">
            <img :src="!satisfied ? iconBumanyiOn : iconBumanyiOff" class="satisfaction-icon" />
            <span>{{ t('review.disatisfied') }}</span>
          </div>
          <div :class="['satisfaction-btn', satisfied ? 'active' : '']" @click="satisfied = true">
            <img :src="satisfied ? iconManyiOn : iconManyiOff" class="satisfaction-icon" />
            <span>{{ t('review.satisfied') }}</span>
          </div>
        </div>
      </div>
      <!-- 评分卡 -->
      <div class="info-card review-score-card">
        <div class="review-score-title">
          {{ t('review.pleaseRateService') }}
        </div>
        <div class="review-score-row">
          <div class="score-label">
            {{ t('review.overallScore') }}
          </div>
          <van-rate v-model="service_score" :size="24" color="#FFD600" void-color="#e7e7e7" />
          <div class="score-value">
            {{ service_score.toFixed(1)
            }}{{ t('review.scoreUnit') }}
          </div>
        </div>
        <div class="review-score-row">
          <div class="score-label">
            {{ t('review.workEfficiency') }}
          </div>
          <van-rate v-model="work_score" :size="24" color="#FFD600" void-color="#e7e7e7" />
          <div class="score-value">
            {{ work_score.toFixed(1) }}{{ t('review.scoreUnit') }}
          </div>
        </div>
        <div class="review-score-row">
          <div class="score-label">
            {{ t('review.communicationExperience') }}
          </div>
          <van-rate v-model="interact_score" :size="24" color="#FFD600" void-color="#e7e7e7" />
          <div class="score-value">
            {{ interact_score.toFixed(1)
            }}{{ t('review.scoreUnit') }}
          </div>
        </div>
      </div>
      <!-- 印象卡 -->
      <div class="info-card review-impression-card">
        <div class="review-impression-title">
          {{ t('review.yourImpression') }}
        </div>
        <div class="impression-tags">
          <div v-for="(tag, i) in tags" :key="i" :class="[
            'impression-tag',
            tag.selected ? 'selected' : '',
          ]" @click="toggleTag(i)">
            {{ tag.text }}
          </div>
          <!-- <div class="impression-tag add-tag">添加印象</div> -->
        </div>
      </div>
      <!-- 签字卡 -->
      <div class="info-card review-sign-card">
        <div class="sign-row">
          <span class="sign-title">{{
            t('review.confirmSignature')
          }}</span>
          <span class="sign-action" @click="goToSign">{{
            sign || orderStore.service.customer_sign ? t('review.seeSign') : t('review.clickSign')
          }}</span>
        </div>
        <!-- <div class="sign-line"></div> -->
        <!-- <div class="sign-file">{{ t('review.file') }}</div> -->
      </div>
      <!-- 评价输入卡 -->
      <div class="info-card review-input-card">
        <div class="review-input-row">
          <span class="input-label">{{ t('review.comment') }}</span>
          <input class="input-field" v-model="comment" :placeholder="t('review.enterComment')" />
        </div>
      </div>
      <!-- 提交按钮 -->
      <div v-if="state == 5" class="submit-btn-bar">
        <button class="submit-btn" @click="submitReview">
          {{ t('review.submit') }}
        </button>
      </div>
    </div>
    <van-popup v-model:show="showSign" position="bottom">
      <div style="display: flex; flex-direction: column">
        <van-signature ref="signatureRef" :pen-color="'#000'" @submit="saveSignature" @clear="onClear"
          clear-button-text="清除" confirm-button-text="确认" style="background: #fff; flex: 1" />
      </div>
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import NavHeader from '@/components/NavHeader.vue'
import { ref, onMounted, watch } from 'vue'
import { showToast } from 'vant'
import {
  getOrderDetailApi,
  getEvaluateTagsList,
  uploadFile,
  submitEvaluate,
} from '@/api/user'
import { useRoute, useRouter } from 'vue-router'
import { useOrderStore } from '@/stores/order'
import { useI18n } from 'vue-i18n'

import iconBumanyiOn from '@/assets/home/icon-bumanyi-on.png'
import iconBumanyiOff from '@/assets/home/icon-bumanyi-off.png'
import iconManyiOn from '@/assets/home/icon-manyi-on.png'
import iconManyiOff from '@/assets/home/icon-manyi-off.png'

const route = useRoute()
const router = useRouter()
const orderStore = useOrderStore()
const { t } = useI18n()

const userName = ref('')

const satisfied = ref(true)
const service_score = ref(0)
const work_score = ref(0)
const interact_score = ref(0)
const comment = ref('')
const tags = ref()
const showSign = ref(false)
const sign = ref('') // 签字图片地址
const signatureRef = ref()
const time = ref()
const state = ref(0)

// 获取订单号，优先从路由参数，其次从store
const order_no = ref('')

function toggleTag(i: number) {
  tags.value[i].selected = !tags.value[i].selected
}

function base64ToFile(base64: string, filename = 'signature.jpg') {
  const arr = base64.split(',')
  const mime = arr[0].match(/:(.*?);/)?.[1] || 'image/jpeg'
  const bstr = atob(arr[1])
  let n = bstr.length
  const u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], filename, { type: mime })
}

async function submitReview() {
  // 校验必填项
  if (!order_no.value) {
    showToast(t('review.noOrderNo'))
    return
  }

  // 判断有无签名且为base64
  if (sign.value && typeof sign.value === 'string' && sign.value.startsWith('data:image')) {
    const file = base64ToFile(sign.value)
    try {
      const res = await uploadFile({ file })
      if (res.data) {
        // 假设后端返回 url
        const url = (res.data.basePath || '') + (res.data.fileName || '')
        sign.value = url
      } else {
        showToast(t('signature uploadFail') || '签名上传失败')
        return
      }
    } catch (e) {
      showToast(t('signature uploadFail') || '签名上传失败')
      return
    }
  }


  if (satisfied.value !== true && satisfied.value !== false) {
    showToast(t('review.selectSatisfaction'))
    return
  }
  const selectedTags = tags.value
    .filter((t: any) => t.selected)
    .map((t: any) => t.text)
  if (!selectedTags.length) {
    showToast(t('review.selectTags'))
    return
  }
  if (interact_score.value === undefined || interact_score.value === null) {
    showToast(t('review.selectInteractScore'))
    return
  }
  if (work_score.value === undefined || work_score.value === null) {
    showToast(t('review.selectWorkScore'))
    return
  }
  if (service_score.value === undefined || service_score.value === null) {
    showToast(t('review.selectServiceScore'))
    return
  }

  const params = {
    order_no: order_no.value,
    evaluate: {
      satisfied: satisfied.value ? 'yes' : 'no',
      tags: selectedTags,
      interact_score: interact_score.value,
      work_score: work_score.value,
      service_score: service_score.value,
      remarks: comment.value,
      sign: sign.value,
    },
  }
  console.log('参数', params)
  submitEvaluate(params).then(() => {
    showToast(t('review.thanks'))
    getOrderDetail()
  })
}

onMounted(() => {
  order_no.value =
    (route.query.order_no as string) || orderStore.order_no || ''
  // 横屏签字，宽高反转
  // windowWidth.value = window.innerWidth
  // windowHeight.value = window.innerHeight
})

function onClear() {
  // showToast('clear')
}
// base64 {image: '', canvas: canvas}
async function saveSignature(data: any) {
  // const base64 = signatureRef.value?.image()
  console.log('base64', data)
  if (!data.image) {
    showToast(t('review.signRequired'))
  } else {
    sign.value = data.image
    showSign.value = false
  }
}
function formatServiceDateTime(service_date: string, service_time: string) {
  // service_date: "2025-05-13"
  // service_time: "04:00,21:04"
  if (!service_date || !service_time) return ''
  // 取出时间段
  const times = service_time.split(',')
  return `${service_date} ${times.join('-')}`
}
onMounted(async () => {
  const { data } = await getEvaluateTagsList()
  // tags.value =
  console.log('标签', data.items)
  tags.value = data.items.map((t: string) => ({
    text: t,
    selected: false,
  }))
  await getOrderDetail()
})

async function getOrderDetail(): Promise<void> {
  const res = await getOrderDetailApi(order_no.value as string)
  if (res.data) {
    const data = res.data
    // 评价相关字段补充到页面属性
    if (data.evaluate) {
      state.value = data.state
      satisfied.value = data.evaluate.satisfied === 'yes'
      service_score.value = data.evaluate.work_score || 5
      work_score.value = data.evaluate.service_score || 5
      userName.value = data.service.member_id
      interact_score.value = data.evaluate.interact_score || 5
      time.value = formatServiceDateTime(
        data.service.service_date,
        data.service.service_time
      )
      comment.value = data.evaluate.remarks || ''
      if (Array.isArray(data.evaluate.tags)) {
        const selectedTags = res.data.evaluate.tags // 用户已选标签数组
        // 遍历tags.value，把已选的selected设为true
        tags.value.forEach((tag: any) => {
          if (selectedTags.includes(tag.text)) {
            tag.selected = true
          }
        })
      }
      // 其它如签字、文件等可按需补充
    }
    // 师傅信息、服务时间等也可补充
    // ...
  }
}

const goToSign = () => {
  router.push({
    path: '/signature',
    query: { from: 'review' },
  })
}

watch(
  () => route.query.sign,
  (val) => {
    if (typeof val === 'string' && val) {
      sign.value = val
    } else if (
      Array.isArray(val) &&
      val.length > 0 &&
      typeof val[0] === 'string'
    ) {
      sign.value = val[0]
    }
  },
  { immediate: true }
)
</script>

<style scoped>
.base-info-page {
  background: #f3f4f6;
  min-height: 100vh;
  padding-bottom: 100px;
}

.info-card-group {
  padding: 32px 0 0 0;
  display: flex;
  flex-direction: column;
  gap: 16px;
  align-items: center;
}

.info-card {
  width: 95%;
  max-width: 450px;
  border-radius: 15px;
  background: #fff;
  box-shadow: none;
  margin: 0;
  border: 1px solid #eee;
  padding: 16px;
  position: relative;
}

.review-master-vertical {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  width: 100%;
}

.review-master-row {
  display: flex;
  align-items: center;
  gap: 16px;
  width: 100%;
}

.review-question-left {
  font-size: 16px;
  font-weight: 600;
  color: #000;
  margin-bottom: 8px;
  margin-left: 0;
  text-align: left;
}

.master-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: #ffcc8a;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.vant-avatar-icon {
  font-size: 36px;
  color: #fff;
}

.master-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.master-name {
  font-size: 14px;
  font-family: 'PingFang SC', sans-serif;
  font-weight: 500;
  color: #000;
}

.master-date {
  font-size: 14px;
  color: #666;
}

.review-satisfaction-row {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-bottom: 8px;
  margin-top: 16px;
}

.satisfaction-btn {
  width: 150px;
  height: 40px;
  border-radius: 10px;
  background: #e7e7e7;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: 600;
  color: #7d7d7d;
  cursor: pointer;
  gap: 8px;
  border: none;
  transition: background 0.2s, color 0.2s;
}

.satisfaction-btn.active {
  background: #ffebbb;
  color: #0c0c0c;
}

.satisfaction-icon {
  width: 22px;
  height: 22px;
}

.review-score-title {
  font-size: 16px;
  font-weight: 600;
  color: #000;
  margin-bottom: 18px;
}

.review-score-row {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

.score-label {
  width: 100px;
  font-size: 14px;
  font-weight: 600;
  color: #0c0c0c;
}

.score-value {
  font-size: 12px;
  font-weight: 600;
  color: #000;
  margin-left: 8px;
}

.review-impression-title {
  font-size: 16px;
  font-weight: 600;
  color: #000;
  margin-bottom: 18px;
}

.impression-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.impression-tag {
  min-width: 90px;
  height: 31px;
  border-radius: 10px;
  background: #e7e7e7;
  color: #0f68fe;
  font-size: 14px;
  font-weight: 600;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  padding: 0 12px;
  transition: background 0.2s, color 0.2s;
}

.impression-tag.selected {
  background: #0f68fe;
  color: #fff;
}

.impression-tag.add-tag {
  background: #ededed;
  color: #7d7d7d;
}

.review-sign-card {
  padding: 0 16px 16px 16px;
}

.sign-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 16px;
}

.sign-title {
  font-size: 16px;
  font-weight: 600;
  color: #000;
}

.sign-action {
  font-size: 14px;
  font-weight: 600;
  color: #b1b1b2;
  cursor: pointer;
}

.sign-line {
  height: 0.5px;
  background: #b0b0b0;
  margin: 12px 0;
  width: 100%;
  /* margin-left: 0.5%; */
}

.sign-file {
  color: #0f68fe;
  font-size: 14px;
  font-weight: 600;
  text-align: center;
  text-decoration: underline;
}

.review-input-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
}

.input-label {
  font-size: 16px;
  font-weight: 600;
  color: #000;
}

.input-field {
  flex: 1;
  border: none;
  outline: none;
  font-size: 14px;
  color: #000;
  background: transparent;
  padding: 8px 0;
}

.submit-btn-bar {
  width: 100%;
  display: flex;
  justify-content: center;
  margin-top: 16px;
}

.submit-btn {
  width: 350px;
  height: 60px;
  border-radius: 10px;
  background: #0065d1;
  color: #fff;
  font-size: 20px;
  font-weight: 600;
  border: none;
  cursor: pointer;
  letter-spacing: -0.3px;
}
</style>
